<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ExampleGenerate } from './orderDetail'
import { GetTuanOrderDetail, GetTuangouTuanOption, PostTuanOrderCreateData, PutTuanOrderModifyData } from '@/api/modules/tuangou'
import detailStore from '@/store/modules/NewCacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<ExampleGenerate>({
  tuanRecId: 0,
  tuanInfoId: 0,
  orderId: 0,
  nickName: '',
  avatar: '',
  productName: '',
  productCon: 0,
  recStatus: 1,
  addTime: '',
})

const tuanInfoOptionList = ref<any[]>([])

const id = route.query.id as string

const rules = reactive({
  tuanInfoId: [
    { required: true, message: '请选择团购ID', trigger: 'blur' },
  ],
  orderId: [
    { required: true, message: '请输入订单ID', trigger: 'blur' },
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
  ],
  avatar: [
    { required: true, message: '请上传头像', trigger: 'blur' },
  ],
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
  productCon: [
    { required: true, message: '请输入购买商品数量', trigger: 'blur' },
  ],
  recStatus: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
  addTime: [
    { required: true, message: '请选择添加时间', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  ruleForm.value[key] = url
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      // console.log(params)

      if (id) {
        // 编辑
        PutTuanOrderModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'tuangouOrder' })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        // console.log(params)

        PostTuanOrderCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('tuanOrderForm')
            router.push({ name: 'tuangouOrder' })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

onMounted(async () => {
  if (id) {
    await GetTuanOrderDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('tuanOrderForm')
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('tuanOrderForm', newValue)
    }
  }, { deep: true })
  const params = {
    PageIndex: 1,
    PageSize: 10000,
  }
  GetTuangouTuanOption(params).then((res: any) => {
    if (res.succeeded) {
      tuanInfoOptionList.value = res.data
    }
  })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="团购信息ID" prop="tuanInfoId">
              <el-select v-model="ruleForm.tuanInfoId" placeholder="请选择团购活动" filterable>
                <el-option
                  v-for="item in tuanInfoOptionList"
                  :key="item.tuanInfoId"
                  :label="`${item.tuanInfoId}--${item.tuanTitle}`"
                  :value="`${item.tuanInfoId}`"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="订单ID" prop="orderId">
              <el-input v-model="ruleForm.orderId" placeholder="请输入订单ID" />
            </ElFormItem>
          </ElCol> -->
          <!-- <ElCol :md="8">
            <ElFormItem label="商品名称" prop="productName">
              <el-input v-model="ruleForm.productName" placeholder="请输入商品名称" />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="购买数量" prop="productCon">
              <el-input v-model="ruleForm.productCon" placeholder="请输入商品名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="添加时间" prop="addTime">
              <el-date-picker
                v-model="ruleForm.addTime"
                type="datetime"
                placeholder="请选择添加时间"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="用户信息">
        <ElRow :gutter="20">
          <ElCol :md="24">
            <ElFormItem label="昵称" prop="nickName">
              <el-input v-model="ruleForm.nickName" placeholder="请输入昵称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="头像" prop="avatar">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.avatar" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'avatar')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
